// ADODatabase.cpp: implementation of the CADODatabase class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ADODatabase.h"

#include "ADORecordset.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CADODatabase::CADODatabase()
{
	m_pConnection = NULL;
	::CoInitialize(NULL);
}

CADODatabase::~CADODatabase()
{
	Close();
	::CoUninitialize();
}

BOOL CADODatabase::Open(CString strProvider, CString strUserName/* =NULL*/, CString strPassword/*=NULL*/)
{
	LPCTSTR pszProvider=(LPCTSTR)strProvider;
	LPCTSTR pszUserName=(LPCTSTR)strUserName;
	LPCTSTR pszPassword=(LPCTSTR)strPassword;
	if(pszProvider) 
	{
		try
		{
			HRESULT hr;
			if(m_pConnection == NULL)
			{
				hr = m_pConnection.CreateInstance(__uuidof(Connection));
				if(FAILED(hr))
				{
					m_pConnection = NULL;
					return FALSE;
				}
				m_pConnection->CursorLocation = adUseClient;
			}
			else if(m_pConnection->State != adStateClosed)
				m_pConnection->Close();
			
			_bstr_t bstrUserName = pszUserName;
			_bstr_t bstrPassword = pszPassword;

			m_pConnection->PutConnectionTimeout(15);
			m_pConnection->PutCommandTimeout(20);
			hr = m_pConnection->Open(_bstr_t(pszProvider),
				bstrUserName, bstrPassword,
				//_T(""),
				//_T(""),
				adModeUnknown);

			if(FAILED(hr))
				return FALSE;
		
			return TRUE;
		}
		catch(_com_error e)
		{
			m_pConnection = NULL;
		}
	}
	return FALSE;
}

void CADODatabase::RollbackTrans()
{
	if(IsOpen())
		m_pConnection->RollbackTrans();
}

void CADODatabase::CommitTrans()
{
	if(IsOpen())
		m_pConnection->CommitTrans();
}

void CADODatabase::BeginTrans()
{
	if(IsOpen())
		m_pConnection->BeginTrans();
}

BOOL CADODatabase::IsOpen()
{
	try
	{
		if(m_pConnection != NULL && m_pConnection->State != adStateClosed)
		return TRUE;
	}
	catch(...)
	{}
	return FALSE;
}

void CADODatabase::Close()
{
	try
	{
		if(IsOpen() &&m_pConnection != NULL)
		m_pConnection->Close();
	}
	catch(...)
	{}
}

_ConnectionPtr CADODatabase::GetConnection()
{
	return m_pConnection;
}

CADORecordset* CADODatabase::Query(CString sQuery)
{
	CADORecordset* padoRecord = NULL;
	if(!sQuery.IsEmpty())
	{
//		padoRecord = new CADORecordset;
//		padoRecord->GetRecordset().CreateInstance(__uuidof(Recordset));
//		padoRecord->GetRecordset()->CacheSize = 10;
////	padoRecord->GetRecordset()->CursorType = adOpenKeyset;
//		padoRecord->GetRecordset()->Open((_bstr_t)sQuery,(_variant_t)m_pConnection,adOpenKeyset,
//			adLockPessimistic,adCmdText);
		padoRecord = new CADORecordset(this);
		padoRecord->Query(sQuery);
	}
	return padoRecord;
}
